package com.lyy.blog.web;

import com.lyy.blog.notfoundeexception;
import com.lyy.blog.service.blogservice;
import com.lyy.blog.service.tagsservice;
import com.lyy.blog.service.typeservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class indexcontroller {

    @Autowired
    private blogservice blogservice;

    @Autowired
    private typeservice typeservice;

    @Autowired
    private tagsservice tagsservice;
    @GetMapping("/")
    public String index(@PageableDefault(size = 8, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                        Model model){
        model.addAttribute("page",blogservice.listblog(pageable));
        model.addAttribute("types",typeservice.listtypetop(6));
        model.addAttribute("tags",tagsservice.listtagtop(10));
        model.addAttribute("recommendblogs",blogservice.listrecommendtop(8));



        return "index";
    }
    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model) {
        model.addAttribute("blog", blogservice.getAndConvert(id));
        return "blog";
    }

    @PostMapping("/search")
    public String search(@PageableDefault(size = 8, sort = {"updateTime"}, direction = Sort.Direction.DESC) Pageable pageable,
                         @RequestParam String query, Model model) {
        model.addAttribute("page", blogservice.listblog("%"+query+"%", pageable));
        model.addAttribute("query", query);
        return "search";
    }


    @GetMapping("/footer/newblog")
    public String newblogs(Model model) {
        model.addAttribute("newblogs", blogservice.listrecommendtop(3));
        return "_fragments :: newblogList";
    }

}
